package model.conversations;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import model.conversations.Conversation;

import view.input.InputWords;

import exceptions.InvalidConversationNumber;

public class ConversationManager implements _ConversationManager{

	ConversationStorage store;
	String key;
	Conversation currentConv;
	String person="";
	
	public ConversationManager(){
		store = new ConversationStorage();
	}
	
	// this function selects the conversation and returns the greeting
	public String selectConversation(String person,int level,char stage) throws InvalidConversationNumber{
		this.person=person;
		key=person+String.valueOf(level)+String.valueOf(stage);
		//the key will be modified soon to include level and stage
		System.out.println(key);
		
			currentConv=store.getConversation(key);
			return currentConv.getGreeting();
	}
	

	public String getReply(InputWords words) {
		return currentConv.getReply(words);
	}


	public boolean getStatusFinalReply() {
		return currentConv.getStatusFinalReply();
	}
	
	
	public String getLastPersonInConversation() {
		return person;
	}
	
	public Conversation selectConversation(String person) throws InvalidConversationNumber{
		Conversation currentConv=store.getConversation(person);
		return currentConv;	
	}
	
	
	public void loadConversationFromFile(String filename) throws IOException  {
		File file = new File(filename);
		BufferedReader reader = new BufferedReader(new FileReader(file));
		
		String delimiter = ",";
		//First line has convName and greeting
        String line = reader.readLine();
        String name = removeQuotation(line.split(delimiter)[0]);
        String greeting = removeQuotation(line.split(delimiter)[1]);
        Conversation c = new Conversation(name,greeting);
        
        while ((line = reader.readLine()) != null){
        	String[] split = line.split(delimiter);
        	int prerequisite = Integer.parseInt(split[0]);
        	String hint = removeQuotation(split[1]);
        	String iSay = removeQuotation(split[2]);
        	String uSay = removeQuotation(split[3]);
        	boolean fin = Boolean.parseBoolean(split[4]);
        	boolean success = Boolean.parseBoolean(split[4]);
        	c.setReply(prerequisite,hint,iSay,uSay,fin,success);
        }
        this.store.setConversation(c);
	}

	public static String removeQuotation(String s){
		if(s.charAt(0)=='"' && s.charAt(s.length()-1)=='"')
			return s.substring(1,s.length()-1);
		return s;
	}
		
}
